package cn.felord.sse.api;

import cn.felord.sse.entity.MessageBody;
import cn.felord.sse.event.NewOrderNotifyEvent;
import cn.felord.sse.event.NewOrderNotifyEventPublisherAware;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 文件名：SseApi.java
 * @create 2019-11-26 10:26
 * @create by Dibbing pan
 *
 * @Description:
 * http://localhost:8099/index
 * http://localhost:8099/send/111
 *
 * 北京中油瑞飞信息技术有限责任公司(http://www.richfit.com)
 * Copyright  2017 Richfit Information Technology Co., LTD. All Right Reserved.
 */
@Controller
public class SseApi {
    private Map<String, SseEmitter> sseEmitters = new HashMap<>();
    @Resource
    private NewOrderNotifyEventPublisherAware newOrderNotifyEventPublisherAware;

    @Value("${watermark.font:微软雅黑2}")
    private String v;

    @GetMapping("/test")
    @ResponseBody
    public String test(){
        System.out.println(v);
        return v;
    }

    @GetMapping(path = "/events/{id}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @CrossOrigin
    public SseEmitter handle(@PathVariable String id) {
        SseEmitter sseEmitter = new SseEmitter();
        this.sseEmitters.put(id, sseEmitter);
        return sseEmitter;
    }


    @GetMapping("/send/{id}")
    @ResponseBody
    public String send(@PathVariable String id){
        Map<String, String> map = new HashMap<>(1);
        map.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        MessageBody<Map<String, String>> body = new MessageBody<>();
        body.setFrom("SERVER");
        body.setTo(id);
        body.setPayload(map);
        SseEmitter emitter=sseEmitters.get(id);
        /*if(null != emitter){
            NewOrderNotifyEvent newOrderNotifyEvent = new NewOrderNotifyEvent("false", body, emitter);
            newOrderNotifyEventPublisherAware.publish(newOrderNotifyEvent);
        }*/
        Optional.of(sseEmitters.get(id)).ifPresent(sseEmitter -> {
                NewOrderNotifyEvent newOrderNotifyEvent = new NewOrderNotifyEvent("false", body, sseEmitter);
                newOrderNotifyEventPublisherAware.publish(newOrderNotifyEvent);
        });
        return "success";
    }


    @GetMapping("/index")
    public String index() {
        return "index.ftl";
    }
}
